package dao

import (
	"chat-room/http/dto"
	"github.com/jinzhu/gorm"
	"time"
)

type Log struct {
	Id        int       `json:"id" gorm:"primary_key" description:"自增主键"`
	RoomId    int       `json:"room_id" gorm:"column:room_id" description:"聊天室Id"`
	UserId    int       `json:"user_id" gorm:"column:user_id" description:"用户ID"`
	Type      int       `json:"type" gorm:"column:type" description:"类型"`
	Content   string    `json:"content" gorm:"column:content" description:"内容`
	IsDelete  int       `json:"is_delete" gorm:"column:is_delete" description:"是否删除"`
	CreatedAt time.Time `json:"create_at" gorm:"column:create_at" description:"创建时间"`
}

type LogDetail struct {
	Id         int       `json:"id"`
	UserName   string    `json:"user_name"`
	Content    string    `json:"content"`
	Type       int       `json:"type"`
	CreateAt   time.Time `json:"create_at"`
	CreateTime string    `json:"create_time"`
}

func (l *Log) TableName() string {
	return "chat_room_log"
}

/**
* @Author: yang
* @Description：聊天列表-查询
* @Date: 2021/10/27 11:49
 */
func (l *Log) List(tx *gorm.DB, in *dto.LogListInput) (list []LogDetail, num int, err error) {
	offset := (in.Page - 1) * in.PageSize
	err = tx.Table(l.TableName()).
		Select("chat_room_log.id, chat_room_log.type, chat_room_log.content, chat_room_log.create_at , chat_room_user.name as user_name").
		Joins("left join chat_room_user ON chat_room_log.user_id = chat_room_user.id").
		Limit(in.PageSize).Offset(offset).Order("chat_room_log.id desc").
		Scan(&list).Error

	for k, v := range list {
		list[k].CreateTime = v.CreateAt.Format("2006-01-02 15:04:05")
	}

	// 倒叙
	l.reverseArr(&list)

	err = tx.Table(l.TableName()).Count(&num).Error
	return
}

/**
 * @Author: yang
 * @Description：数组倒叙
 * @Date: 2021/11/3 14:01
 */
func (l *Log) reverseArr(arr *[]LogDetail) {
	var temp LogDetail
	length := len(*arr)
	for i := 0; i < length/2; i++ {
		temp = (*arr)[i]
		(*arr)[i] = (*arr)[length-1-i]
		(*arr)[length-1-i] = temp
	}
}
